import { memo, useEffect, useState, useCallback } from 'react'
import { View, Swiper } from '@tarojs/components'

import './index.scss'

export default memo(function Tab(props) {
  const { className, tabList, initTab, onChangeTab, onChangeSwipe, children } = props;
  const [ currentId, setCurrentId ] = useState(0);

  useEffect(() => {
    if (!initTab) {
      setCurrentId(tabList?.[0]?.['id']);
    } else {
      setCurrentId(initTab);
    }
  }, [])

  const innerStyle = {
    width: `${100 / (tabList.length ?? 0)}%`,
    transform: `translateX(${currentId * 100}%)`
  }

  const handleClick = useCallback((id) => {
    setCurrentId(id);
    onChangeTab?.(id);
  }, [onChangeTab])

  const handleChangeSwiper = (e) => {
    const id = e.detail.current;
    setCurrentId(id);
    onChangeSwipe?.(e);
  }


  return (
    <View className={`tab-container ${className}`}>
      <View className="tab-bar">
        {
          tabList?.map(item => {
            return (
              <View className={`tab-item ${ currentId === item.id ? 'active' : '' }`} key={item.id} onClick={() => handleClick(item.id)}>{item.label}</View>
            )
          })
        }
        <View className="scroll-bar" style={innerStyle}></View>
      </View>
      {/* 选项卡内容 */}
      <Swiper
        current={currentId}
        className="tab-content"
        onChange={handleChangeSwiper}
      >
        {children}
      </Swiper>
    </View>
  )
})
